<?php
namespace Admin\Controller;

use Common\Controller\AdminbaseController;

class GosController extends AdminbaseController{
    
	protected $ad_model;
	
	public function _initialize() {
		parent::_initialize();	
		//寄件人信息
		$list = array(
		    '2' =>array(
		        array('name'=>'Akasugu海外旗舰店1','account'=>'800000811004','sname'=>'大野贡市'
		    ,'scountry'=>'日本','scity'=>'大阪','saddr'=>'大阪市大正区泉尾4-12-2-C'
		    ,'sphone'=>'080-61140031'),
		        array('name'=>'Akasugu海外旗舰店2','account'=>'800000811004','sname'=>'大野贡市'
            ,'scountry'=>'日本','scity'=>'大阪','saddr'=>'大阪市大正区泉尾4-12-2-C'
            ,'sphone'=>'080-61140031')
		),
		    '3' =>array(
		        array('name'=>'Akasugu海外旗舰店3','account'=>'800000811004','sname'=>'大野贡市'
		        ,'scountry'=>'日本','scity'=>'大阪','saddr'=>'大阪市大正区泉尾4-12-2-C'
		        ,'sphone'=>'080-61140031')		        
		    ),
		    '4' =>array(
		        array('name'=>'Akasugu海外旗舰店4','account'=>'800000811004','sname'=>'大野贡市'
		        ,'scountry'=>'日本','scity'=>'大阪','saddr'=>'大阪市大正区泉尾4-12-2-C'
		        ,'sphone'=>'080-61140031')		        
		    ),
		);
		if(session('ADMIN_ID') != 1){
		    $data = $list[session('ADMIN_ID')];
		    unset($list);
		    $list = $data;
		}else{
		    foreach ($list as $k=>$v){
		      foreach ($v as $ks=>$vs){
		          if(count($vs)>0) $data[]=$vs;
		      }
		    }
		    unset($list);
		    $list=$data;
		}
		$this->seller = $list[I('id')];
		$this->assign('list',$list);
	}
	
	public function index(){
	    $this->display();
	}
	
	public function updateGos(){
	    $upload = new \Think\Upload();// 实例化上传类
	    $upload->maxSize   =     3145728 ;// 设置附件上传大小
	    $upload->exts      =     array('xlsx','xls');// 设置附件上传类型
	    $upload->rootPath  =     C("UPLOADPATH"); // 设置附件上传根目录
	    $upload->savePath  =     ''; // 设置附件上传（子）目录
	    // 上传文件
	    $info   =   $upload->upload();
	    if(!$info) {// 上传错误提示错误信息
	        $this->error($upload->getError());
	    }else{// 上传成功   */
	        vendor("Excel.PHPExcel");
	        $file_name=$upload->rootPath.$info['photo']['savepath'].$info['photo']['savename'];
	        $objPHPExcel = \PHPExcel_IOFactory::load($file_name,$encode='utf-8');
	        $sheet = $objPHPExcel->getSheet(0);
	        $highestRow = $sheet->getHighestRow(); // 取得总行数
	        $highestColumn = $sheet->getHighestColumn(); // 取得总列数
	        $objdata = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
	        foreach($objdata[1] as $k=>$v){
	            $v = str_replace(array("\r\n", "\r", "\n"),'',$v);
	            switch ($v)
	            {
	                case "订单号":
	                    $key_ename = $k;
	                    break;
	                case "买家昵称":
	                    $maijia = $k;
	                    break;
	                case "收件人":
	                    $shoujianren = $k;
	                    break;
	                case "电话":
	                    $dianhua = $k;
	                    break;
	                case "省":
	                    $shen = $k;
	                    break;
	                case "市":
	                    $shi = $k;
	                    break;
	                case "区":
	                    $qv = $k;
	                    break;
	                case "地址":
	                    $dizhi = $k;
	                    break;
	
	                case "宝贝名称":
	                    $baby = $k;
	                    break;
	                case "属性":
	                    $shuxin = $k;
	                    break;
	                case "数量":
	                    $shuliang = $k;
	                    break;
	                case "退款状态":
	                    $tuikuan = $k;
	                    break;
	                case "买家留言":
	                    $maijialiuyan = $k;
	                    break;
	                case "卖家备注":
	                    $maijiabeizhu = $k;
	                    break;
	            }
	        }
	        for($i=2;$i<=$highestRow;$i++)
	        {
	            $obj = $objdata[$i];
	            $sn = $obj[$key_ename];
	            $data[$i]['A'] = $sn;
	            $data[$i]['D'] = $this->seller['account'];
	            $data[$i]['F'] = $obj[$shoujianren];
	            $data[$i]['G'] = $obj[$shoujianren];
	            $data[$i]['H'] = $sn;
	            $data[$i]['I'] = '中国';
	            $data[$i]['J'] = $obj[$shen];
	            $data[$i]['L'] = $obj[$shen].$obj[$shi].$obj[$qv].$obj[$dizhi];
	            $data[$i]['N'] = $obj[$dianhua];
	            $data[$i]['Q'] =$this->seller['sname'];
	            $data[$i]['R'] =$this->seller['scountry'];
	            $data[$i]['S'] =$this->seller['scity'];
	            $data[$i]['V'] =$this->seller['saddr'];
	            $data[$i]['U'] =$this->seller['name'];
	            $data[$i]['X'] =$this->seller['sphone'];
	            $data[$i]['goods'] = $obj[$baby];
	            $data[$i]['num'] = $obj[$shuliang];
	            $data[$i]['shoujianren'] = $obj[$shoujianren];
	        }
	        foreach ($data as $v){
	            $k = $v['A'];
	            if(!isset($result[$k])){
	                $result[$k] = $v;
	            }
	            $result[$k]['temp'][] = 1;
	            $c = count($result[$k]['temp']);
	            $result[$k]['AI']  = isset($result[$k]['AI'])?$result[$k]['AI'].' '.$v['goods'].' x'.$v['num']:$v['goods'].' x'.$v['num'];
	            $result[$k]['goods_num'] = $result[$k]['goods_num']+$v['num'];
	            $result[$k]['request'] = isset($result[$k]['request'])?$result[$k]['request'].'\n'.$c.'、'.$v['goods'].' x'.$v['num']:$c.'、'.$v['goods'].' x'.$v['num'];
	        }
	        foreach ($result as $k=>$v){
	            $result[$k]['AW'] = $result[$k]['request'] .'\n 内件总数：' .$v['goods_num'];
	            $result[$k]['AO'] = $v['goods_num'];
	             
	        }
	        //http://www.sdhack.com/20121163.html
	        $file_name = './Public/gos.xls';
	        $objPHPExcel = \PHPExcel_IOFactory::load($file_name,$encode='utf-8');
	        $sheet = $objPHPExcel->getSheet(0);
	        $highestRow = $sheet->getHighestRow(); // 取得总行数
	        $highestColumn = $sheet->getHighestColumn(); // 取得总列数
	        $objdata = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
	         
	
	        $fileName = 'GOS';
	        foreach ($objdata[1] as $k=>$v){
	            $headArr[$k] =  str_replace(array("\r\n", "\r", "\n"),'',$v);
	        }
	        foreach ($objdata[1] as $k=>$v ){
	            $keys[$k]='';
	        }
	        foreach ($result as $k=>$v){
	            $result[$k]=array_merge($keys,$v);
	            unset($result[$k]['request']);
	            unset($result[$k]['goods_num']);
	            unset($result[$k]['goods']);
	            unset($result[$k]['shoujianren']);
	            unset($result[$k]['num']);
	            unset($result[$k]['temp']);
	        }
	        $this->test($result,$headArr,$fileName);
	         
	         
	    }
	     
	}
	
	
	/**
	 * 导出数据为excel表格
	 *@param $data    一个二维数组,结构如同从数据库查出来的数组
	 *@param $title   excel的第一行标题,一个数组,如果为空则没有标题
	 *@param $filename 下载的文件名
	 *@examlpe
	 $stu = M ('User');
	 $arr = $stu -> select();
	 exportexcel($arr,array('id','账户','密码','昵称'),'文件名!');
	 */
	function exportexcel($data=array(),$title=array(),$filename='report'){
	    header("Content-type:application/octet-stream");
	    header("Accept-Ranges:bytes");
	    header("Content-type:application/vnd.ms-excel");
	    header("Content-Disposition:attachment;filename=".$filename.".xls");
	    header("Pragma: no-cache");
	    header("Expires: 0");
	    //导出xls 开始
	    if (!empty($title)){
	        foreach ($title as $k => $v) {
	            $title[$k]=iconv("UTF-8", "GB2312",$v);
	        }
	        $title= implode("\t", $title);
	        echo "$title\n";
	    }
	    if (!empty($data)){
	        foreach($data as $key=>$val){
	            foreach ($val as $ck => $cv) {
	                $data[$key][$ck]=iconv("UTF-8", "GB2312", $cv);
	            }
	            $data[$key]=implode("\t", $data[$key]);
	
	        }
	        echo implode("\n",$data);
	    }
	}
	public function test($data=array(),$expCellName=array(),$filename='report'){
	    vendor("Excel.PHPExcel");
	    $objPHPExcel = new \PHPExcel();
	    $objPHPExcel->getActiveSheet(0)->getColumnDimension('A')->setWidth(40);
	    $objPHPExcel->getActiveSheet(0)->getRowDimension(1)->setRowHeight(35);
	    $objPHPExcel->getActiveSheet(0)->freezePane("A2");
	    $objPHPExcel->getActiveSheet(0)->freezePane("E2");
	    $keys = array_keys(reset($data));
	
	    foreach ($keys as $k=>$v){
	        $objPHPExcel->getActiveSheet(0)->getColumnDimension($v)->setWidth(20);
	        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($v.'1', $expCellName[$v]);
	        if(strstr($expCellName[$v],'*')){
	            $objPHPExcel->getActiveSheet(0)->getStyle($v.'1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
	            $objPHPExcel->getActiveSheet(0)->getStyle($v.'1')->getFill()->getStartColor()->setARGB(\PHPExcel_Style_Color::COLOR_YELLOW);
	        }/*else{
	        $objPHPExcel->getActiveSheet(0)->getStyle($v.'1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
	        $objPHPExcel->getActiveSheet(0)->getStyle( $v.'1')->getFill()->getStartColor()->setARGB("118899");//
	        }*/
	    }
	
	    $dataNum = count($data);
	    for($i=0;$i<$dataNum;$i++){
	        for($j=0;$j<$listNum;$j++){
	            $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+2), $data[$i][$j]);
	        }
	    }
	    $i=1;
	    foreach ($data as $k=>$v){
	        $i++;
	        foreach ($v as $kk=>$kv){
	            $objPHPExcel->getActiveSheet(0)->setCellValueExplicit($kk.$i, $kv,\PHPExcel_Cell_DataType::TYPE_STRING);
	        }
	    }
	    header('pragma:public');
	    header('Content-type:application/vnd.ms-excel;charset=utf-8;name=GOS.xls"');
	    header("Content-Disposition:attachment;filename=GOS.xls");//attachment新窗口打印inline本窗口打印
	    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
	    $objWriter->save('php://output');
	}
	
	
	
}